package cn.skyclass.beans
{
	import cn.skyclass.utils.FlexUtil;
	
	import flash.utils.getDefinitionByName;
	
	import mx.events.PropertyChangeEvent;
	
	/**
	 * IBean 的基本实现，另外提供一些常用方法。
	 */
	[Bindable]
	public class BaseBean extends FlexBean implements IBaseBean, IUIBean, ICloneable
	{		
		// implements IBaseBean
		private var _id:int = 0;
		public function get id():int{
			return this._id;
		}
		public function set id(value:int):void{
			this._id = value;
		}
		
		private var _longId:Number = 0;
		public function get longId():Number{
			return this._longId;
		}
		public function set longId(value:Number):void{
			this._longId = value;
		}
		
		
		// implements IUIBean
		[Transient]
		public function get label():String{
			return this.toString();
		}
		
		[Transient]
		public function get toolTip():String{
			return "";
		}
			
		
		// implements IBaseBean
		public function equals(other:Object):Boolean{
			// 如果引用相等，返回 true
			if(this == other){ return true; }
			
			var b:BaseBean = other as BaseBean;			
			if(b == null){ return false; }
			
			var thisName:String = FlexUtil.getQualifiedClassName(this);	
			var objName:String = FlexUtil.getQualifiedClassName(other);	
			var claEq:Boolean = (thisName == objName);
			var idEq:Boolean = this.useLongId() ? (this.longId == b.longId) : (this.id == b.id);
			return claEq && idEq;
		}			
		
		
		// implements ICloneable method
		public function clone():Object{
			var n:String = FlexUtil.getQualifiedClassName(this);
			var cla:Class = getDefinitionByName(n) as Class;
			var b:BaseBean = new cla() as BaseBean;
			b.copyProperties(this);
			return b;
		}
				
		// 额外提供的方法
		
		
		/**
		 * 发布自身的属性发生改变的事件
		 */
		public function propertyChanged(property:Object=null, 
			oldValue:Object=null, newValue:Object=null):void{
			var e:PropertyChangeEvent = PropertyChangeEvent.createUpdateEvent(
				this, property, oldValue, newValue);
			dispatchEvent(e);
		}
				
		/**
		 * 完成实例的数据初始化工作(类似构造函数的功能)
		 * 
		 * @arg 初始化过程所需的参数
		 */		
		public function init(arg:Object=null):void{
			this.id = 0;
			this.longId = 0;
		}	
		
		/**
		 * 提交数据时完成对数据的合法性验证
		 * 若数据不合法，则返回描述信息字符串，否则返回空字符串 ""
		 * 
		 * @arg 验证数据所需的辅助参数
		 */		
		public function validate(arg:Object=null):String{
			return "";
		}
			
		/**
		 * 此实例的字符串表示形式，如：[object BaseBean] -- id:1
		 */		
		override public function toString():String{
			var out:String = super.toString();
			if(this.useLongId()){
				out += " -- longId:" + this.longId;
			}else{
				out += " -- id:" + this.id;
			}
			return out;
		}		
		
		protected function useLongId():Boolean{
			return this.longId > 0;
		}
	}
}